import random

from django.http import HttpResponse
from django.shortcuts import render
from django_redis import get_redis_connection

# Create your views here.
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from . import constants,serializers

# image_code/(image_code_id[\w-]+)



class ImageCodeView(APIView):
    """接受参数，校验参数，生成图片验证码，将验证码存储到redis中，返回图片
    因为判断出来，他不需要数据库的操作，也不需要校验参数"""

    # 因为url中uuid通过正则验证过了，所以不需要在验证参数
    def get(self, request, image_code_id):
        from meiduo_mall.libs.captcha.captcha import captcha
        text, image = captcha.generate_captcha()
        print(type(text),text)
        redis_conn = get_redis_connection('verify_codes')
        print(image_code_id,type(image_code_id))
        redis_conn.setex(image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        return HttpResponse(image, content_type='image/jpg')


class SMSCodeView(GenericAPIView):
    serializer_class = serializers.SendSmsSerializer

    # 取到手机号，验证码，uuid，
    # 判断数据是否正确(序列化器)
    # 将短信验证码发送过去，并且存储到redis中，而且需要添加发送时间（判断用户在1分钟之内不允许再次发送短信）
    def get(self,request,mobile):
        s = self.get_serializer(data = request.query_params)
        s.is_valid(raise_exception=True)
        send_msg = '%06d'%random.randint(0,999999)
        redis_conn = get_redis_connection('verify_codes')
        # redis_conn.setex('msm_' + mobile,constants.SMS_CODE_REDIS_EXPIRES,send_msg)
        # redis_conn.setex(mobile,constants.SEND_SMS_CODE_INTERVAL,1)
        pl = redis_conn.pipeline()
        pl.setex('msm_' + mobile,constants.SMS_CODE_REDIS_EXPIRES,send_msg)
        pl.setex(mobile,constants.SEND_SMS_CODE_INTERVAL,1)
        pl.execute()

        # from celery_tasks.sms import tasks as sms_takes
        # sms_takes.send_sms_code.delay(mobile,send_msg,constants.USER_SMS_CODE_REPIRES)
        print('='*20,send_msg)
        redis_conn.get('msm_' + mobile)

        return Response({'message':'ok'})